//
//  AuthenticationViewController.m
//  WideHelp
//
//  Created by ENERGY on 2018/8/13.
//  Copyright © 2018年 ENERGY. All rights reserved.
//

#import "AuthenticationViewController.h"
#import "AuthenticationTableViewCell.h"
@interface AuthenticationViewController ()<UITableViewDelegate, UITableViewDataSource>
@property (nonatomic, strong)UITableView * tableView;
@property (nonatomic, strong)UIView * headerView;
@property (nonatomic, strong)NSMutableArray * cellTitleArr;
@property (nonatomic, strong)UIView * footerView;
@property (nonatomic, strong)NSString * realNameStr;
@property (nonatomic, strong)NSString * cardID;
@end

@implementation AuthenticationViewController(networking)
- (void)authUser{
    NSDictionary * dic = @{
        @"userId":[UserModel sharedInstanced].userID,
        @"cookie":[UserModel sharedInstanced].cookie,
        @"relaname":self.realNameStr,
        @"card_id":self.cardID
    };
    [self showprogressHUD];
    [[AFAppDotNetAPIClient sharedClient] POST:@"user/authUser" parameters:dic progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        [self hiddenProgressHUD];
        if ([responseObject[@"msg"] isEqualToString:@"success"]) {
            ShowMessage(@"认证成功");
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                [self.navigationController popViewControllerAnimated:YES];
            });
        }else{
            ShowMessage(responseObject[@"msg"]);
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        [self hiddenProgressHUD];
        [self showError:error];
    }];
}
@end
@implementation AuthenticationViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.navigationItem.title = @"实名认证";
    if (@available(iOS 11.0, *)) {
        self.tableView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
    }else {
        self.automaticallyAdjustsScrollViewInsets = NO;
    }
    [self.view addSubview:self.tableView];
}
- (UIView *)headerView{
    if (!_headerView) {
        _headerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 33/WIDTH_6_SCALE)];
        _headerView.backgroundColor = getColor(@"f5f5f5");
        //顶部线
        UIView * topLineView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 1/WIDTH_6_SCALE)];
        topLineView.backgroundColor = getColor(@"f1f1f1");
        [_headerView addSubview:topLineView];
        //顶部说明
        UILabel * topInstructionLab = [[UILabel alloc] initWithFrame:CGRectMake(15/WIDTH_6_SCALE, 0, SCREEN_WIDTH - 30/WIDTH_6_SCALE, _headerView.height)];
        [self label:topInstructionLab withFont:DEF_FontSize_12 withText:@"为保障您的个人权益，请尽快完成实名认证" withTextColor:getColor(@"9b9b9b") withTextAlignment:NSTextAlignmentLeft withView:_headerView withBGColor:[UIColor clearColor]];
    }return _headerView;
}
- (UITableView *)tableView{
    if (!_tableView) {
        _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT - BOTTOM_HEIGHT) style:UITableViewStylePlain];
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        _tableView.rowHeight = 41/WIDTH_6_SCALE;
        [_tableView registerClass:[AuthenticationTableViewCell class] forCellReuseIdentifier:NSStringFromClass([AuthenticationTableViewCell class])];
        _tableView.backgroundColor = [UIColor whiteColor];
        _tableView.tableHeaderView = self.headerView;
        _tableView.tableFooterView = self.footerView;
    }return _tableView;
}
- (UIView *)footerView{
    if (!_footerView) {
        _footerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 72/WIDTH_6_SCALE)];
        _footerView.backgroundColor = [UIColor whiteColor];
        UIButton * authenticationBtn = [[UIButton alloc] initWithFrame:CGRectMake(15/WIDTH_6_SCALE, 16/WIDTH_6_SCALE, SCREEN_WIDTH - 30/WIDTH_6_SCALE, 40/WIDTH_6_SCALE)];
        [self button:authenticationBtn withBGColor:getColor(greenBGColor) withLayerBorderColor:nil withLayerBorderWith:0 withCornerRadius:4 withMasksToBounds:YES withViwe:_footerView];
        [authenticationBtn setTitle:@"立即认证" forState:UIControlStateNormal];
        [authenticationBtn addTarget:self action:@selector(authenticationBtnClick:) forControlEvents:UIControlEventTouchUpInside];
        [authenticationBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        authenticationBtn.titleLabel.font = DEF_FontSize_14;
    }return _footerView;
}
- (NSMutableArray *)cellTitleArr{
    if (!_cellTitleArr) {
        _cellTitleArr = @[@{@"title":@"姓名", @"placeHolder":@"请输入您的真实姓名"},
                          @{@"title":@"身份证号", @"placeHolder":@"请输入身份证号"}].mutableCopy;
    }return _cellTitleArr;
}
#pragma mark - tableViewDelegate和tableViewDataSource
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    AuthenticationTableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:NSStringFromClass([AuthenticationTableViewCell class]) forIndexPath:indexPath];
    cell.model = self.cellTitleArr[indexPath.row];
    if (indexPath.row == 0) {
        //姓名
        [cell.contentTextFidle addTarget:self action:@selector(nameTextFieldEvent:) forControlEvents:UIControlEventEditingChanged];
    }
    if (indexPath.row == 1) {
        //身份证号码
        [cell.contentTextFidle addTarget:self action:@selector(idCardNumFieldEvent:) forControlEvents:UIControlEventEditingChanged];
    }
    return cell;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return 2;
}
#pragma mark - action
//姓名
- (void)nameTextFieldEvent:(UITextField *)sender{
    NSLog(@"姓名");
    NSLog(@"%@",sender.text);
    self.realNameStr = sender.text;
}
//身份证号码
- (void)idCardNumFieldEvent:(UITextField *)sender{
    NSLog(@"身份证号码");
    NSLog(@"%@",sender.text);
    self.cardID = sender.text;
}
- (void)authenticationBtnClick:(UIButton *)sender{
    if (self.realNameStr.length == 0 || self.realNameStr == nil || [self.realNameStr isEqualToString:@""]) {
        ShowMessage(@"请填写姓名");
        return;
    }
    if ([[self class] checkUserID:self.cardID] == NO) {
        ShowMessage(@"请正确填写身份证号码");
        return;
    }
    if (self.cardID.length == 0 || self.cardID == nil || [self.cardID isEqualToString:@""]) {
        ShowMessage(@"请填写身份证号码");
        return;
    }
    [self authUser];//认证
}
//18位身份证格式和合法性验证
+(BOOL)checkUserID:(NSString *)userID
{
    //长度不为18的都排除掉
    if (userID.length!=18) {
        return NO;
    }
    
    //校验格式
    NSString *regex2 = @"^(^[1-9]\\d{7}((0\\d)|(1[0-2]))(([0|1|2]\\d)|3[0-1])\\d{3}$)|(^[1-9]\\d{5}[1-9]\\d{3}((0\\d)|(1[0-2]))(([0|1|2]\\d)|3[0-1])((\\d{4})|\\d{3}[Xx])$)$";
    NSPredicate *identityCardPredicate = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",regex2];
    BOOL flag = [identityCardPredicate evaluateWithObject:userID];
    
    if (!flag) {
        return flag;    //格式错误
    }else {
        //格式正确在判断是否合法
        
        //将前17位加权因子保存在数组里
        NSArray * idCardWiArray = @[@"7", @"9", @"10", @"5", @"8", @"4", @"2", @"1", @"6", @"3", @"7", @"9", @"10", @"5", @"8", @"4", @"2"];
        
        //这是除以11后，可能产生的11位余数、验证码，也保存成数组
        NSArray * idCardYArray = @[@"1", @"0", @"10", @"9", @"8", @"7", @"6", @"5", @"4", @"3", @"2"];
        
        //用来保存前17位各自乖以加权因子后的总和
        NSInteger idCardWiSum = 0;
        for(int i = 0;i < 17;i++)
        {
            NSInteger subStrIndex = [[userID substringWithRange:NSMakeRange(i, 1)] integerValue];
            NSInteger idCardWiIndex = [[idCardWiArray objectAtIndex:i] integerValue];
            
            idCardWiSum+= subStrIndex * idCardWiIndex;
            
        }
        
        //计算出校验码所在数组的位置
        NSInteger idCardMod=idCardWiSum%11;
        
        //得到最后一位身份证号码
        NSString * idCardLast= [userID substringWithRange:NSMakeRange(17, 1)];
        
        //如果等于2，则说明校验码是10，身份证号码最后一位应该是X
        if(idCardMod==2)
        {
            if([idCardLast isEqualToString:@"X"]||[idCardLast isEqualToString:@"x"])
            {
                return YES;
            }else
            {
                return NO;
            }
        }else{
            //用计算出的验证码与最后一位身份证号码匹配，如果一致，说明通过，否则是无效的身份证号码
            if([idCardLast isEqualToString: [idCardYArray objectAtIndex:idCardMod]])
            {
                return YES;
            }
            else
            {
                return NO;
            }
        }
    }
}
@end
